import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import watermark from '../../../common/watermark.js';
import { Collaboration_APP, TEST_NUMBER, YY_NUMBER } from '../../../../../public/js/config/config.js';
import { requestDict, DictionaryType } from '../../../common/dictionary/dictionary-type.js';

(function (window, document, $) {
    let getEntryInfo = [],
        getWeighInfo = [],
        _speLevelList,
        _pigTypeList = [];
    const _json = Utils.ParsingUrl(window.location);
    const looksalesTemplate = doT.template($('#looksalesplan-template').text());
    const lksalesmainTemplate = doT.template($('#looksalesplanmain-template').text());
    const orderAdvancesTemplate = doT.template($('#orderAdvances-template').text());

    //解决ios浏览器返回不刷新问题
    window.addEventListener('pageshow', function (e) {
        //如果检测到页面是从“往返缓存”中读取的，刷新页面
        if (e.persisted) {
            window.location.reload();
        }
    });

    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _watermarkBgImg();
    });
    //销售品类
    requestDict(DictionaryType.LEVEL_TYPE).then((res) => {
        _speLevelList = res.data;
        _initCommand();
    });

    //返回列表
    $(document).on('click', '#returnlist', function () {
        location.href = `../saleorders/saleorders.html?v=${Utils.GetTime()}`;
    });

    //过磅信息确认
    $(document).on('click', '#looksalesEntry div[data-flag=table-click-edit]', function () {
        let seq = $(this).attr('data-seq');
        let count = $(this).attr('data-count');
        let weight = $(this).attr('data-weight');
        let attaches = $(this).attr('data-attaches');
        let material = $(this).attr('data-material');
        let breedBatchName = $(this).attr('data-breedBatchName');
        let breedBatchId = $(this).attr('data-breedBatchId');
        let planQty = $(this).attr('data-planQty');
        let estimatedAvgWeight = $(this).attr('data-estimatedAvgWeight');
        let unitPrice = $(this).attr('data-unitPrice');
        let bizDate = $(this).attr('data-bizDate');
        let cstm = $(this).attr('data-cstm');
        let salePer = $(this).attr('data-salePer');
        let farmOrgId = $(this).attr('data-farmOrgId');
        let farmOrgName = $(this).attr('data-farmOrgName');
        let deiver = $(this).attr('data-deiver');
        let carNo = $(this).attr('data-carNo');
        let transferCarNo = $(this).attr('data-transferCarNo');
        let saleOrgId = $(this).attr('data-saleOrgId');
        let saleOrgName = $(this).attr('data-saleOrgName');
        let cstmId = $(this).attr('data-cstmId');
        let cstmName = $(this).attr('data-cstmName');
        let isGift = $(this).attr('data-isGift');
        let materialId = $(this).attr('data-materialId');
        let baseMeasureUnit = $(this).attr('data-baseMeasureUnit');
        let deliveryRegion = $(this).attr('data-deliveryRegion');
        let shipRegion = $(this).attr('data-shipRegion');
        let pigType = $(this).attr('data-pigType');
        let materialName = $(this).attr('data-materialName');
        let materialNumCode = $(this).attr('data-materialNumCode');
        let subMeasureUnit = $(this).attr('data-subMeasureUnit');
        let specLevelId = $(this).attr('data-specLevelId');
        let deiverName = $(this).attr('data-deiverName');
        let deiverPhone = $(this).attr('data-deiverPhone');
        let billNo = $(this).attr('data-billNo');
        let planOrderId = $(this).attr('data-planOrderId');
        let receiveAddress = $(this).attr('data-receiveAddress');
        let detailDeliveryAddress = $(this).attr('data-detailDeliveryAddress');

        getWeighInfo = [];
        let info = {
            count: count == 'null' ? '' : count,
            weight: weight == 'null' ? '' : weight,
            material: material,
            breedBatchName: breedBatchName,
            planQty: planQty == 'null' ? '' : planQty,
            estimatedAvgWeight: estimatedAvgWeight,
            unitPrice: unitPrice,
            breedBatchId: breedBatchId,
            bizDate: bizDate,
            cstm: cstm,
            salePer: salePer,
            farmOrgName: farmOrgName,
            deiver: deiver,
            carNo: carNo,
            transferCarNo: transferCarNo,
            saleOrgId: saleOrgId,
            saleOrgName: saleOrgName,
            cstmId: cstmId,
            cstmName: cstmName,
            isGift: isGift,
            farmOrgId: farmOrgId,
            materialId: materialId,
            deliveryRegion: deliveryRegion,
            shipRegion: shipRegion,
            pigType: pigType,
            baseMeasureUnit: baseMeasureUnit,
            materialName: materialName,
            materialNumCode: materialNumCode,
            subMeasureUnit: subMeasureUnit,
            specLevelId: specLevelId,
            deiverName: deiverName,
            deiverPhone: deiverPhone,
            billNo: billNo,
            planOrderId: planOrderId,
            receiveAddress: receiveAddress,
            detailDeliveryAddress: detailDeliveryAddress,
        };
        getWeighInfo.push(info);
        JSON.stringify(Utils.SetSessionStorage('getWeighInfo', getWeighInfo));

        location.href = `../saleorders/replenish.html?v=${Utils.GetTime()}&orderId=${getUrlKey('id')}&seq=${parseInt(seq)}&count=${count}&weight=${weight}&attaches=${attaches}&pigType=${pigType}`;
    });

    //修改订单车辆信息
    $(document).on('click', '#looksalesEntry div[data-flag=table-click-vehicle]', function () {
        let seq = $(this).attr('data-seq');
        let carNo = $(this).attr('data-carNo');
        let deiverId = $(this).attr('data-deiverId');
        let breedBatchName = $(this).attr('data-breedBatchName');
        let count = $(this).attr('data-count');
        let orderCount = $(this).attr('data-orderCount');
        let weight = $(this).attr('data-weight');
        let deiverName = $(this).attr('data-deiverName');
        let deiverPhone = $(this).attr('data-deiverPhone');
        let deiverNumCode = $(this).attr('data-deiverNumCode');
        let transferCarNo = $(this).attr('data-transferCarNo');
        let bizDate = $(this).attr('data-bizDate');
        let cstm = $(this).attr('data-cstm');
        let salePer = $(this).attr('data-salePer');
        let farmOrgName = $(this).attr('data-farmOrgName');

        getEntryInfo = [];
        let info = {
            count: count == 'null' ? '' : count,
            breedBatchName: breedBatchName,
            orderCount: orderCount,
            weight: weight == 'null' ? '' : weight,
            deiverName: deiverName,
            deiverNumCode: deiverNumCode,
            carNo: carNo,
            transferCarNo: transferCarNo,
            bizDate: bizDate,
            cstm: cstm,
            salePer: salePer,
            farmOrgName: farmOrgName,
            deiverPhone: deiverPhone,
        };
        getEntryInfo.push(info);
        JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));

        location.href = `../saleorders/vehicle.html?v=${Utils.GetTime()}&orderId=${getUrlKey('id')}&seq=${parseInt(seq)}&carNo=${carNo}&deiverId=${deiverId}&deiverName=${deiverName}&deiverPhone=${deiverPhone}`;
    });

    //预收款
    //$(document).on('click', '#looksalesMain div[data-flag=table-click-payment]', function () {
    //    location.href = `../saleorders/paymentorders.html?v=${Utils.GetTime()}&orderId=${getUrlKey("id")}`;
    //});

    //命令初始化
    const _initCommand = async () => {
        await requestDict(DictionaryType.PIG_FIXEDPRICE_TYPE).then((res) => {
            _pigTypeList = res.data;
        });
        saleOrdersAPI.querySalesInfo(getUrlKey('id')).then((res) => {
            let entry = {
                billStatus: res.billStatus,
                bizDate: moment(res.bizDate).format('YYYY-MM-DD'),
                cstmName: res.cstmName,
                cstmNumCode: res.cstmNumCode,
                salePerName: res.salePerName,
                salePerNumCode: res.salePerNumCode,
                saleOrgId: res.saleOrgId,
                saleOrgName: res.saleOrgName,
                cstmId: res.cstmId,
                cstmName: res.cstmName,
                pigType: res.pigType,
                pigTypeName: _pigTypeList.find((s) => s.value == res.pigType)?.displayName || '',
            };
            res.entreis = res.entreis.map((item) => {
                item.specLevelId = item.specLevel;
                item.billNo = res.billNo;
                item.planOrderId = res.planOrderId;

                let specLevel = '';
                let receiveAddress = '';
                let detailDeliveryAddress = '';
                let countNum = 0;
                if (Utils.IsNotNull(item.shipRegion)) {
                    let areaId = item.shipRegion.split('|');
                    let split = areaId[1].split(';');
                    receiveAddress = split[0] + split[1] + split[2] + split[3] + item.shipAddress;
                } else {
                    receiveAddress = item.shipAddress;
                }
                if (Utils.IsNotNull(item.deliveryRegion)) {
                    let areaId = item.deliveryRegion.split('|');
                    let split = areaId[1].split(';');
                    detailDeliveryAddress = split[0] + split[1] + split[2] + split[3] + item.deliveryAddress;
                } else {
                    detailDeliveryAddress = item.deliveryAddress;
                }
                if (Utils.IsNotNull(_speLevelList.find((s) => s.value == item.specLevel))) {
                    specLevel = _speLevelList.find((s) => s.value == item.specLevel).displayName;
                } else {
                    specLevel = item.specLevel;
                }
                if (!Utils.IsNotNull(item.count)) {
                    countNum = 0;
                } else {
                    countNum = item.count || 0;
                }
                return { ...item, specLevel, receiveAddress, detailDeliveryAddress, countNum };
            });
            res.pigTypeName = _pigTypeList.find((s) => s.value == res.pigType)?.displayName || '';
            $('#looksalesMain').empty().append(lksalesmainTemplate(res));
            $('#looksalesEntry')
                .empty()
                .append(looksalesTemplate({ entreis: res.entreis, entry: entry }));
            if (Utils.IsNotNull(res.attaches)) {
                _viewImages(res.attaches, 'uploaderFiles');
            }
        });
        if (_json.isAdvance == 'true') {
            let advance = await saleOrdersAPI.getOrderAdvances(_json.id);
            $('#orderAdvances').empty().append(orderAdvancesTemplate(advance));
            if (Utils.IsNotNull(advance.attaches)) {
                _viewImages(advance.attaches, 'advance-uploaderFiles');
            }
        }
    };
    /** 获取地址栏的 参数  传入 字段返回值 */
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    //附件回显
    const _viewImages = async (images, id) => {
        let _imag = images.split(',');
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then((_res) => {
                    if (_res.isSucceed) {
                        let _li;
                        if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        }
                        $(`#${id}`).append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
        }
        $(document).on('click', `#${id}`, function (e) {
            let target = e.target;
            while (!target.classList.contains(`weui-uploader__file`) && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
            });
            $('.weui-icon_gallery-delete').css('display', 'none');
        });
    };
    //添加水印信息
    const _watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage('SNAccountEply')) || {};
        watermark.set(_userInfo.name + _userInfo.numCode); // 水印
        //saleOrdersAPI.queryUserName(Utils.GetQueryString('state') || YY_NUMBER.sourceID).then(res => {
        //    watermark.set(_userInfo.un + res.code);// 水印
        //}).catch(_ => {
        //    watermark.set(_userInfo.un);// 水印
        //});
    };
})(window, document, jQuery);
